package com.roobo.demo;

import android.content.Context;
import android.media.MediaRecorder;
import android.util.Log;
import android.widget.Toast;

/**
 * 音频录制
 */
public class MyRecordCenter {

    public static final String TAG = MyRecordCenter.class.getSimpleName();

    private MediaRecorder mRecorder = null;
    private Context mContext;
    private long mStartRecordTime;
    private int mVoiceDuration;

    public MyRecordCenter(Context context) {
        this.mContext = context.getApplicationContext();
    }

    /***
     * 开始录制
     * @param voicePath
     * @return
     */
    public boolean startRecord(String voicePath) {
        boolean isSuccess = false;
        if (!VoiceChatActivity.isSdCardExist()) {
            Log.v(TAG, "createVoiceFile isSdCardExist=false");
            return isSuccess;
        }
        if (mRecorder == null) {
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.setOutputFile(voicePath);
            try {
                mRecorder.prepare();
                mRecorder.start();
                mStartRecordTime = System.currentTimeMillis();
                isSuccess = true;
            } catch (Exception e) {
                Log.d(TAG, "startRecord e.getLocalizedMessage:" + e.getLocalizedMessage());
                Toast.makeText(mContext, mContext.getResources().getString(R.string.start_record_device_fail), Toast.LENGTH_SHORT).show();
                stopRecord();
            }
        } else {
            Log.d(TAG, "startRecord " + mContext.getResources().getString(R.string.recording));
        }
        return isSuccess;
    }

    /***
     * 停止录制，释放资源
     * @return
     */
    public boolean stopRecord() {
        boolean isSuccess = false;
        if (mRecorder != null) {
            try {
                mRecorder.stop();
                mRecorder.release();
                isSuccess = true;
                mVoiceDuration = (int) ((System.currentTimeMillis() - mStartRecordTime) / 1000);
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "stopRecord e.getLocalizedMessage:" + e.getLocalizedMessage());
                Toast.makeText(mContext, mContext.getResources().getString(R.string.stop_record_fail), Toast.LENGTH_SHORT).show();
            }
            mRecorder = null;
        }
        return isSuccess;
    }

    /**
     * 获取音频时长
     * @return
     */
    public int getVoiceDuration() {
        if (mVoiceDuration < 0) {
            mVoiceDuration = 0;
        }
        return mVoiceDuration;
    }
}
